package com.tuozixuan.onesql;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.tuozixuan.onesql.db.Column;
import com.tuozixuan.onesql.db.ConnectionInfo;
import com.tuozixuan.onesql.db.LocalDataSource;
import com.tuozixuan.onesql.mysql.BaseDao;
import com.tuozixuan.onesql.service.ConnectionInfoService;
import com.tuozixuan.onesql.service.impl.ConnectionInfoServiceImpl;
import com.tuozixuan.onesql.ui.MainMenu;
import com.tuozixuan.onesql.ui.NavigationView;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;

public class OneSqlApplication extends Application {
    
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 1000, 500, Color.WHITE);
        
        MainMenu mainMenu = new MainMenu().build(primaryStage);
        root.setTop(mainMenu.getMenuBar());
        
        BorderPane masterBorderPane = new BorderPane();
        //masterBorderPane.setTop(tabPane);
        //masterBorderPane.setBottom(table);
        
        /**
        TreeItem<String> treeItemRoot = new TreeItem<>("NoteRoot");
        treeItemRoot.setExpanded(true);
        List<Database> databaseList = new BaseDao().getDatabaseList();
        for (Database database : databaseList) {
            TreeItem<String> treeItem = new TreeItem<>(database.getName());
            treeItemRoot.getChildren().add(treeItem);
            
            List<Table> tableList = new BaseDao().getTableList(database.getName());
            for (Table table : tableList) {
                TreeItem<String> tableTreeItem = new TreeItem<>(table.getName());
                treeItem.getChildren().add(tableTreeItem);
            }
        }
        
        TreeTableColumn<String, String> treeTableColumn = new TreeTableColumn<>("Column");
        treeTableColumn.setPrefWidth(300);
        treeTableColumn.setCellValueFactory((CellDataFeatures<String, String> p) -> new ReadOnlyStringWrapper(p.getValue().getValue()));
        
        
        TreeTableView<String> treeTableView = new TreeTableView<String>(treeItemRoot);
        treeTableView.getColumns().addAll(treeTableColumn);
        treeTableView.setShowRoot(false);
        treeTableView.setPrefWidth(300);
        
        treeTableView.setOnMouseClicked(mouseEvent -> {
            if (mouseEvent.getClickCount() == 2) {
                System.out.println("====" + mouseEvent.getSource() + "======"+ mouseEvent.getTarget());
                
                TreeItem<String> item = treeTableView.getSelectionModel().getSelectedItem();
                System.out.println("Selected Text : " + item.getValue());
                
                
                try {
                    this.openTable(masterBorderPane, item.getValue());
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        */

        ConnectionInfoService connectionInfoService = new ConnectionInfoServiceImpl();
        List<ConnectionInfo> connectionInfoList = connectionInfoService.getAll();
        LocalDataSource.INSTANCE.init(connectionInfoList);
        
        NavigationView navigationView = new NavigationView(masterBorderPane, connectionInfoList);
        root.setLeft(navigationView.getTreeTableView());
        
        
        
        /* ===================表格======================== */
        //TableView table = new TableView();
        //ObservableList<Map<String,Object>> tableData = this.buildTableData1();
        
        //new MapValueFactory(tableData);
//        List<Column> columnList = new BaseDao().getColumnList("user");
//        for (Column column : columnList) {
//            TableColumn tableColumn = new TableColumn(column.getName());
//            tableColumn.setCellValueFactory(new MapValueFactory(column.getName()));
//            table.getColumns().add(tableColumn);
//        }
//        table.setItems(tableData);
        
//        Callback<TableColumn, TableCell> cellFactory = 
//                new Callback<TableColumn, TableCell>() {
//                    public TableCell call(TableColumn p) {
//                        return new EditingCell();
//                }
//            };

//            firstNameCol.setCellFactory(cellFactory);
//            lastNameCol.setCellFactory(cellFactory);
//            emailCol.setCellFactory(cellFactory);
            
            //table.setEditable(true);

            /**
            //Modifying the firstName property
            firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
                @Override public void handle(CellEditEvent<Person, String> t) {
                    ((Person)t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setFirstName(t.getNewValue());
                }
            });

            //Modifying the lastName property
            lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
                @Override public void handle(CellEditEvent<Person, String> t) {
                    ((Person)t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setLastName(t.getNewValue());
                }
            }); 

            //Modifying the email property
            emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() {
                @Override public void handle(CellEditEvent<Person, String> t) {
                    ((Person)t.getTableView().getItems().get(
                        t.getTablePosition().getRow())).setEmail(t.getNewValue());
                 }
            });*/
        
        //table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
        //table.setPrefWidth(800);
        //table.autosize();
        //root.setCenter(table);
        
        //BorderPane masterBorderPane = new BorderPane();
        //masterBorderPane.setTop(tabPane);
        //masterBorderPane.setBottom(table);
        root.setCenter(masterBorderPane);
        
        
        Rectangle2D screenRectangle = Screen.getPrimary().getBounds();
        double screenWidth = screenRectangle.getWidth();
        double screenHeight = screenRectangle.getHeight();
        
        primaryStage.setScene(scene);
        primaryStage.setTitle("OneSql");
        primaryStage.setHeight(screenHeight);
        primaryStage.setWidth(screenWidth);
        primaryStage.setX(10);
        primaryStage.setY(10);
        primaryStage.show();
    }
    
    private ObservableList<Map<String,Object>> buildTableData1() {
        List<Map<String,Object>> dataList = new BaseDao().query("select * from user");
        ObservableList<Map<String,Object>> tableData = FXCollections.observableArrayList(dataList);
        return tableData;
    }
    
   private void openTable(BorderPane masterBorderPane, String tableName) throws SQLException {
       TableView table = new TableView();
       ObservableList<Map<String,Object>> tableData = this.buildTableData1();
       
       //new MapValueFactory(tableData);
       List<Column> columnList = new BaseDao().getColumnList(tableName);
       for (Column column : columnList) {
           TableColumn tableColumn = new TableColumn(column.getName());
           tableColumn.setCellValueFactory(new MapValueFactory(column.getName()));
           table.getColumns().add(tableColumn);
       }
       table.setItems(tableData);
       
       table.setEditable(true);
       table.autosize();
       
       masterBorderPane.setBottom(table);
   }

}
